import { Request, Response } from "express";
import userServer from '../service/UserServer'
import { encryption, decrypt, createToken } from '../utils/index'

class UserController {

  // 注册用户
  async register(req: Request, res: Response) {
    const form = req.body
    form.password = encryption(form.password) // 密码加密
    const result = await userServer.save(form)
    res.send({
      status: 200,
      msg: '注册成功！'
    })    
  }

  // 登录
  async login(req: Request, res: Response) {
    const {phone, password} = req.body
    const user = await userServer.findOneByPhone(phone)
    const isRight = decrypt(password, String(user.password)) // 密码比较 
    if (!isRight) return res.send({status: 400, msg: '密码错误！'})
    const token = createToken(Number(user.id))  // 生成 token
    delete user.password;
    res.send({
      meta: { status: 200, msg: '登录成功！', },
      data: { user, token}
    })
  }

  // 分页查询所有用户， 如果不传参数，默认查询全部
  async findAll(req: Request, res: Response) {
    const total = await userServer.userCount()
    const { page_num, page_size } = req.query
    // 计算skip
    let skip = (parseInt(page_num) - 1) * parseInt(page_size)
    const result = await userServer.find(skip, parseInt(page_size))
    res.send({
      meta: { status: 200, msg: '查询成功！', },
      data: { total, list: result }
    })
  }

}
export default new UserController()